<template>
  <div class="address-map" role="application" aria-label="地图应用">
    <!-- 语言切换按钮 -->
    <div class="language-switcher">
      <button
        v-for="lang in ['zh', 'en']"
        :key="lang"
        @click="changeLanguage(lang)"
      >
        {{ lang === "zh" ? "中文" : "English" }}
      </button>
    </div>
    <!-- 搜索栏 -->
    <div class="search-container">
      <input
        id="tipinput"
        v-model="address"
        :placeholder="$t('inputAddress')"
        @input="debouncedHandleInput"
        @keyup.enter="manualSearch"
        :aria-label="$t('inputAddress')"
      />
      <button
        class="search-btn"
        @click="manualSearch"
        :aria-label="$t('search')"
      >
        <i class="fas fa-search"></i> {{ $t("search") }}
      </button>
      <button class="clear-btn" @click="clearSearch" :aria-label="$t('clear')">
        <i class="fas fa-times"></i> {{ $t("clear") }}
      </button>
    </div>
    <!-- 地图和搜索结果面板容器 -->
    <div class="map-panel-container">
      <div id="map-container"></div>
      <div class="panels-container">
        <div id="address_panel" role="region" aria-label="搜索结果">
          <h2>{{ $t("searchResults") }}</h2>
          <div
            v-for="(result, index) in paginatedResults"
            :key="index"
            class="search-result-item"
            @click="focusOnResult(result)"
            @dblclick="addToTargetPanel(result)"
            @contextmenu.prevent="showContextMenu($event, index, 'address')"
          >
            <h3>{{ result.name }}</h3>
            <p>{{ result.address }}</p>
            <p>{{ $t("type") }}: {{ result.type }}</p>
            <p v-if="result.tel">{{ $t("tel") }}: {{ result.tel }}</p>
            <p>
              {{ $t("location") }}: {{ result.location.lng.toFixed(6) }},
              {{ result.location.lat.toFixed(6) }}
            </p>
          </div>
          <div class="pagination" v-if="totalPages > 1">
            <button @click="changePage(-1)" :disabled="currentPage === 1">
              {{ $t("previous") }}
            </button>
            <span>{{ currentPage }} / {{ totalPages }}</span>
            <button
              @click="changePage(1)"
              :disabled="currentPage === totalPages"
            >
              {{ $t("next") }}
            </button>
          </div>
        </div>

        <!-- 新增：按钮容器 -->
        <div class="panel-buttons">
          <button
            class="show-locations-btn"
            @click="showAllLocations"
            :aria-label="$t('showLocations')"
          >
            <i class="fas fa-map-marker-alt"></i> {{ $t("showLocations") }}
          </button>
          <button
            class="optimal-route-btn"
            @click="calculateOptimalRoute"
            :aria-label="$t('optimalRoute')"
          >
            <i class="fas fa-route"></i> {{ $t("optimalRoute") }}
          </button>
          <button
            class="export-data-btn"
            @click="exportData"
            :aria-label="$t('exportData')"
          >
            <i class="fas fa-file-export"></i> {{ $t("exportData") }}
          </button>
        </div>

        <div id="target_panel" role="region" aria-label="目标结果">
          <h2>{{ $t("targetResults") }}</h2>
          <div
            v-for="(result, index) in paginatedTargetResults"
            :key="index"
            class="search-result-item"
            @click="focusOnResult(result)"
            @contextmenu.prevent="showContextMenu($event, index, 'target')"
          >
            <h3>{{ result.name }}</h3>
            <p>{{ result.address }}</p>
            <p>{{ $t("type") }}: {{ result.type }}</p>
            <p v-if="result.tel">{{ $t("tel") }}: {{ result.tel }}</p>
            <p>
              {{ $t("location") }}: {{ result.location.lng.toFixed(6) }},
              {{ result.location.lat.toFixed(6) }}
            </p>
          </div>
          <div class="pagination" v-if="targetTotalPages > 1">
            <button
              @click="changeTargetPage(-1)"
              :disabled="targetCurrentPage === 1"
            >
              {{ $t("previous") }}
            </button>
            <span>{{ targetCurrentPage }} / {{ targetTotalPages }}</span>
            <button
              @click="changeTargetPage(1)"
              :disabled="targetCurrentPage === targetTotalPages"
            >
              {{ $t("next") }}
            </button>
          </div>
        </div>
      </div>
    </div>
    <!-- 添加右键菜单 -->
    <div v-if="showMenu" :style="menuStyle" class="context-menu">
      <div @click="deleteResult">{{ $t("delete") }}</div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, computed } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { useI18n } from "vue-i18n";
import { useToast } from "vue-toastification"; //洁、优雅的Vue 3通知组件
import { debounce } from "lodash-es"; //防抖函数
import * as XLSX from "xlsx";

export default {
  name: "AddressMap",
  setup() {
    const { t, locale } = useI18n();
    const toast = useToast();
    const address = ref("");
    const map = ref(null);
    const mapModule = ref(null);
    const autoComplete = ref(null);
    const placeSearch = ref(null);
    const currentMarker = ref(null);
    const searchResults = ref([]);
    const currentPage = ref(1);
    const itemsPerPage = 5;
    const searchResult = ref(null);
    const targetResults = ref([]);
    const targetCurrentPage = ref(1);
    const showMenu = ref(false);
    const menuStyle = ref({
      top: "0px",
      left: "0px",
    });
    const selectedIndex = ref(-1);
    const selectedPanelType = ref("");

    // 初始化地图
    const initMap = async () => {
      try {
        const AMap = await AMapLoader.load({
          key: import.meta.env.VITE_AMAP_KEY,
          version: "2.0",
          plugins: [
            "AMap.Scale",
            "AMap.ToolBar",
            "AMap.Geolocation",
            "AMap.AutoComplete",
            "AMap.PlaceSearch",
            "AMap.CitySearch",
          ],
        });

        mapModule.value = AMap;
        map.value = new AMap.Map("map-container", {
          viewMode: "3D",
          zoom: 12,
          center: [120.564, 30.63], // 桐乡市的经纬度坐标
        });

        map.value.addControl(new AMap.Scale());
        map.value.addControl(new AMap.ToolBar());
        map.value.addControl(new AMap.Geolocation());

        initSearch();
        map.value.on("click", onMapClick);

        // 移除 locateCurrentCity() 调用，因为我们现在直接设置了中心点
      } catch (error) {
        handleError(t("mapLoadFailed"));
      }
    };

    // 定位当前城市并设置地图中心（现在不会自动调用，但保留以备将来使用）
    const locateCurrentCity = () => {
      const citySearch = new mapModule.value.CitySearch();
      citySearch.getLocalCity((status, result) => {
        if (status === "complete" && result.info === "OK") {
          map.value.setBounds(result.bounds);
        } else {
          map.value.setCenter([120.564, 30.63]); // 如果定位失败，默认定位到桐乡市
        }
      });
    };

    // 初始化自动完成和地点搜索功能
    const initSearch = () => {
      autoComplete.value = new mapModule.value.AutoComplete({
        input: "tipinput",
      });
      autoComplete.value.on("select", onSelect);

      placeSearch.value = new mapModule.value.PlaceSearch({
        map: map.value,
        pageSize: 5, // 将页面大小设置为5
        autoFitView: true,
      });
    };

    // 处理地点选择事件
    const onSelect = (e) => {
      searchAndAddMarker(e.poi.name, e.poi.adcode);
    };

    // 在地图上添加或更新标记
    const addMarker = (
      location,
      iconUrl = "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png"
    ) => {
      if (currentMarker.value) {
        currentMarker.value.setMap(null);
      }
      currentMarker.value = new mapModule.value.Marker({
        position: location,
        map: map.value,
        icon: new mapModule.value.Icon({
          size: new mapModule.value.Size(25, 34),
          image: iconUrl,
          imageSize: new mapModule.value.Size(25, 34),
        }),
      });
    };

    // 搜索地点并在地图上添加标记
    const searchAndAddMarker = (searchText, adcode = "") => {
      if (adcode) placeSearch.value.setCity(adcode);
      placeSearch.value.search(searchText, (status, result) => {
        if (status === "complete" && result.info === "OK") {
          if (result.poiList.pois.length > 0) {
            // 清空现有的搜索结果
            searchResults.value = [];

            // 获取前5条搜索结果
            const newResults = result.poiList.pois.slice(0, 5).map((poi) => ({
              name: poi.name,
              address: poi.address,
              type: poi.type,
              tel: poi.tel,
              location: poi.location,
            }));

            // 将新结果添加到搜索结果数组
            searchResults.value = newResults;

            // 重置到第一页
            currentPage.value = 1;

            // 添加第一个结果的标记到地图
            addMarker(newResults[0].location);
            map.value.setCenter(newResults[0].location);
            map.value.setZoom(15);

            saveSearchHistory(searchText);
          } else {
            handleError(t("noResults"));
          }
        } else {
          handleError(t("searchFailed"));
        }
      });
    };

    // 执行手动搜索
    const manualSearch = () => {
      if (address.value) {
        searchAndAddMarker(address.value);
      }
    };

    // 清除搜索结果和地图标记
    const clearSearch = () => {
      address.value = "";
      searchResults.value = [];
      if (currentMarker.value) {
        currentMarker.value.setMap(null);
        currentMarker.value = null;
      }
    };

    // 处理地图点击事件，显示点击位的地址信息
    const onMapClick = (e) => {
      mapModule.value.plugin("AMap.Geocoder", () => {
        const geocoder = new mapModule.value.Geocoder();
        geocoder.getAddress(e.lnglat, (status, result) => {
          if (status === "complete" && result.info === "OK") {
            const addr = result.regeocode.formattedAddress;
            address.value = addr;
            toast.info(`${t("clickedLocation")}：${addr}`);
          }
        });
      });
    };

    // 显示错误提示
    const handleError = (message) => toast.error(message);

    // 保存搜索历史到本地存储
    const saveSearchHistory = (address) => {
      let history = JSON.parse(localStorage.getItem("searchHistory") || "[]");
      if (!history.includes(address)) {
        history.unshift(address);
        history = history.slice(0, 10);
        localStorage.setItem("searchHistory", JSON.stringify(history));
      }
    };

    // 切换界面语言
    const changeLanguage = (lang) => {
      locale.value = lang;
    };

    // 处理搜索输入
    const handleInput = (event) => {
      if (event.target.value && autoComplete.value) {
        autoComplete.value.search(event.target.value);
      }
    };

    // 使用防抖处理搜索输入
    const debouncedHandleInput = debounce(handleInput, 300);

    // 计算当前页面显示的搜索结果
    const paginatedResults = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      const end = start + itemsPerPage;
      return searchResults.value.slice(start, end);
    });

    // 计算总页数
    const totalPages = computed(() => {
      return Math.ceil(searchResults.value.length / itemsPerPage);
    });

    // 切换页面
    const changePage = (direction) => {
      const newPage = currentPage.value + direction;
      if (newPage >= 1 && newPage <= totalPages.value) {
        currentPage.value = newPage;
      }
    };

    // 计算当前页面显示的目标结果
    const paginatedTargetResults = computed(() => {
      const start = (targetCurrentPage.value - 1) * itemsPerPage;
      const end = start + itemsPerPage;
      return targetResults.value.slice(start, end);
    });

    // 计算目标结果的总页数
    const targetTotalPages = computed(() => {
      return Math.ceil(targetResults.value.length / itemsPerPage);
    });

    // 切换目标结果页面
    const changeTargetPage = (direction) => {
      const newPage = targetCurrentPage.value + direction;
      if (newPage >= 1 && newPage <= targetTotalPages.value) {
        targetCurrentPage.value = newPage;
      }
    };

    // 规划路线（未在当前代码中使用，可能用于未来功能）
    const planRoute = (start, end) => {
      mapModule.value.plugin("AMap.Driving", () => {
        const driving = new mapModule.value.Driving({
          map: map.value,
          panel: "address_panel",
        });
        driving.search(start, end);
      });
    };

    // 从本地存储获取搜索历史
    const getSearchHistory = () => {
      return JSON.parse(localStorage.getItem("searchHistory") || "[]");
    };

    const searchHistory = ref(getSearchHistory());

    // 聚焦到搜索结果
    const focusOnResult = (result) => {
      if (result) {
        map.value.setCenter(result.location);
        map.value.setZoom(17);
      }
    };

    // 显示所有位置（修改为使用 targetResults）
    const showAllLocations = () => {
      if (targetResults.value.length === 0) {
        toast.info(t("noLocationsToShow"));
        return;
      }

      // 清除当前标记
      if (currentMarker.value) {
        currentMarker.value.setMap(null);
      }

      // 创建标记数组
      const markers = [];

      // 为每个目标结果添加标记
      targetResults.value.forEach((result, index) => {
        const marker = new mapModule.value.Marker({
          position: result.location,
          map: map.value,
          label: {
            content: `${index + 1}`,
            direction: "top",
          },
        });
        markers.push(marker);
      });

      // 调整地图视图以包含所有标记
      map.value.setFitView(markers, {
        padding: [50, 50, 50, 50], // 可以调整这个值来控制缩放级别
      });
    };

    // 计算最优路径（修改为汽车驾车路径）
    const calculateOptimalRoute = () => {
      if (targetResults.value.length < 2) {
        toast.info(t("notEnoughLocationsForRoute"));
        return;
      }

      mapModule.value.plugin("AMap.Driving", () => {
        const driving = new mapModule.value.Driving({
          map: map.value,
          panel: "target_panel",
          policy: mapModule.value.DrivingPolicy.LEAST_TIME, // 设置为最短时间策略
        });

        const waypoints = targetResults.value
          .slice(1, -1)
          .map((result) => result.location);

        driving.search(
          targetResults.value[0].location,
          targetResults.value[targetResults.value.length - 1].location,
          {
            waypoints: waypoints,
            avoidPolygons: [], // 避让区域
            avoidRoad: "", // 避让道路
            province: "浙江省", // 针对起点和终点在同一城市设置，可以避免路径错误
            number: "浙A", // 车牌号，用于判断是否限行
          },
          (status, result) => {
            if (status === "complete") {
              toast.success(t("routeCalculated"));
            } else {
              toast.error(t("routeCalculationFailed"));
            }
          }
        );
      });
    };

    // 添加到目标面板
    const addToTargetPanel = (result) => {
      if (!targetResults.value.some((item) => item.name === result.name)) {
        targetResults.value.unshift(result);
        toast.success(t("addedToTargetPanel"));
      } else {
        toast.info(t("alreadyInTargetPanel"));
      }
    };

    // 显示右键菜单
    const showContextMenu = (event, index, panelType) => {
      event.preventDefault();
      showMenu.value = true;
      menuStyle.value.top = `${event.clientY}px`;
      menuStyle.value.left = `${event.clientX}px`;
      selectedIndex.value = index;
      selectedPanelType.value = panelType;
    };

    // 删除搜索结果
    const deleteResult = () => {
      if (selectedIndex.value !== -1) {
        const results =
          selectedPanelType.value === "target" ? targetResults : searchResults;
        const currentPageRef =
          selectedPanelType.value === "target"
            ? targetCurrentPage
            : currentPage;
        const actualIndex =
          (currentPageRef.value - 1) * itemsPerPage + selectedIndex.value;
        results.value.splice(actualIndex, 1);
        showMenu.value = false;

        // 如果当前页没有结果了，就回到上一页
        if (
          (selectedPanelType.value === "target"
            ? paginatedTargetResults
            : paginatedResults
          ).value.length === 0 &&
          currentPageRef.value > 1
        ) {
          currentPageRef.value--;
        }

        toast.success(t("resultDeleted"));
      }
    };

    // 点击其他地方时隐藏菜单
    const hideContextMenu = () => {
      showMenu.value = false;
    };

    // 导出数据
    const exportData = () => {
      const data = targetResults.value.map((result) => ({
        名称: result.name,
        地址: result.address,
        经度: result.location.lng,
        纬度: result.location.lat,
      }));

      const ws = XLSX.utils.json_to_sheet(data);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "目标地点");

      XLSX.writeFile(wb, "高德地图导入.xlsx");

      toast.success(t("dataExported"));
    };

    onMounted(() => {
      document.addEventListener("click", hideContextMenu);
      initMap();
    });

    onUnmounted(() => {
      document.removeEventListener("click", hideContextMenu);
      if (map.value) {
        map.value.destroy();
      }
    });

    return {
      address,
      manualSearch,
      clearSearch,
      changeLanguage,
      debouncedHandleInput,
      paginatedResults,
      totalPages,
      currentPage,
      changePage,
      planRoute,
      searchHistory,
      searchResult,
      focusOnResult,
      searchResults,
      showAllLocations,
      calculateOptimalRoute,
      targetResults,
      paginatedTargetResults,
      targetTotalPages,
      targetCurrentPage,
      changeTargetPage,
      addToTargetPanel,
      showMenu,
      menuStyle,
      showContextMenu,
      deleteResult,
      exportData,
    };
  },
};
</script>

<style src="../styles/AddressMap.css" scoped></style>

<style scoped>
.map-panel-container {
  display: flex;
  width: 100%;
  height: calc(100vh - 150px); /* 调整高度以适应页面 */
}

#map-container {
  flex: 1;
  min-width: 75%; /* 确保地图至少占据75%宽度 */
  height: 100%; /* 使地图填满容器高度 */
}

.panels-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow-y: auto;
  max-height: calc(100vh - 150px);
  width: 25%; /* 设置宽度为25% */
}

#address_panel,
#target_panel {
  background-color: white;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px;
  overflow-y: auto;
  max-height: calc(45% - 30px); /* 调整高度以适应新的按钮容器 */
  width: 100%;
  box-sizing: border-box;
}

/* 新增：按钮容器样式 */
.panel-buttons {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
}

.show-locations-btn,
.optimal-route-btn,
.export-data-btn {
  padding: 8px 12px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.show-locations-btn:hover,
.optimal-route-btn:hover,
.export-data-btn:hover {
  background-color: #45a049;
}

.context-menu {
  position: fixed;
  background: white;
  border: 1px solid #ccc;
  padding: 5px 0;
  box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.context-menu div {
  padding: 5px 20px;
  cursor: pointer;
}

.context-menu div:hover {
  background-color: #f0f0f0;
}
</style>
